package com.sdksoft.readcard

import android.content.Intent
import android.util.Log
import android.view.View
import com.csht.bean.IdCardData
import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.csht.listener.ReadCardListener
import com.sdksoft.readcard.databinding.ActivityNfcYjzBinding
import com.csht.utils.HHTipUtils
import com.csht.utils.NfcUtils

/**
 * NFC 外国永久居住证
 */
class NFCYJZActivity : BaseInitActivity(), ReadCardListener {
    //1.声明一个nfc的Adapter
    private lateinit var nfcUtils: NfcUtils

    private val TAG = "readcard"

    private lateinit var activityNfcHuzhaoBinding: ActivityNfcYjzBinding

    private var isInitOk = false

    override fun initView() {
        super.initView()
        setTitleText("NFC外国人永居证")
        activityNfcHuzhaoBinding = ActivityNfcYjzBinding.inflate(layoutInflater)
        baseActivityBinding.llContent.apply{
            addView(activityNfcHuzhaoBinding.root, 0)
        }
        nfcUtils = NfcUtils(this, this.javaClass)
        readSettingBuilder.buildReadCardType(ReadCardType.NFC)
        initSDK()
    }

    /**
     * 初始化SDK
     */
    private fun initSDK() {
        if (readCardManager.readCardType() === ReadCardType.NFC) {
            readCardManager.readCardInit(object : InitListener {
                override fun onResponse(code: Int, msg: String) {
                    when (code) {
                        StatusCode.ININ_ING.code -> {
                            Log.d(TAG, "初始化中. $msg")
                        }
                        StatusCode.ININ_OK.code -> {
                            isInitOk = true
                            runOnUiThread {
                                HHTipUtils.getInstance().showToast(this@NFCYJZActivity, "初始化成功")
                            }
                        }
                        else -> {
                            isInitOk = false
                            runOnUiThread {
                                HHTipUtils.getInstance().showToast(this@NFCYJZActivity, "初始化失败")
                            }
                        }
                    }
                }
            })
        }
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart")
        //此处adapter需要重新获取，否则无法获取message
        nfcUtils.nfcInit( this,  this.javaClass)
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume")
        //设置处理优于所有其他NFC的处理
        nfcUtils.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause")
        //恢复默认状态
        nfcUtils.onPause(this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        if (isInitOk.not()) {
            HHTipUtils.getInstance().showToast(this@NFCYJZActivity, "没有初始化成功")
            return
        }
        activityNfcHuzhaoBinding.apply {
            HHTipUtils.getInstance()
                .showProgressDialog(this@NFCYJZActivity, "读取中，请勿移动", false)
            // 开始读取
            activityNfcHuzhaoBinding.tvMsg.text = "开始读卡---->"
            activityNfcHuzhaoBinding.ivHead.setImageResource(0)
            readCardManager.readCardStart(
                intent, this@NFCYJZActivity
            )
        }
    }

    override fun onReadCardState(type: Int, msg: String?) {
        if (type == 1022) { //读卡失败
            HHTipUtils.getInstance().dismissProgressDialog()
        }
        if (type != StatusCode.READCARD_SUCCESS.code) {
            activityNfcHuzhaoBinding.tvMsg.apply {
                append("\n状态码：$type")
                append("\n消息：$msg")
                append("\n-------------------------")
            }
            mainHandler.postDelayed(
                {
                    activityNfcHuzhaoBinding.logScroll.fullScroll(View.FOCUS_DOWN)
                },
                200
            )
        }
    }

    override fun onReadICCardSuccess(icNumber: String?, type: Int) {
    }

    override fun onReadIDCardSuccess(bean: IdCardData?) {
        HHTipUtils.getInstance().dismissProgressDialog()
        bean?.apply {
            bitmap?.let { bitmap ->
                activityNfcHuzhaoBinding.ivHead.setImageBitmap(bitmap)
            }
            activityNfcHuzhaoBinding.tvMsg.apply {
                text = "读取成功："
                when (type) {
                    StatusCode.CARD_IDCARD_FOREIGN.code,StatusCode.CARD_IDCARD_FOREIGN_OLD.code -> { // 外国永久居住证
                        append("\n中文姓名：")
                        append(nameChinese)
                        append("\n英文姓名：")
                        append(nameEnglish)
                        append("\n性别：")
                        append(sex)
                        append("\n生日：")
                        append(birthday)
                        append("\n国籍：")
                        append(nationlity)
                        append("\n证件号码：")
                        append(bean.id)
                        append("\n有效期限：")
                        append(startDate)
                        append(" - ")
                        append(endDate)
                    }
                    StatusCode.CARD_IDCARD.code -> { // 中国居民身份证
                        append("\n姓名：")
                        append(name)
                        append("\n性别：")
                        append(sex)
                        append("\n民族：")
                        append(nation)
                        append("\n生日：")
                        append(birthday)
                        append("\n住址：")
                        append(address)
                        append("\n证件号码：")
                        append(bean.id)
                        append("\n签发机关：")
                        append(bean.issue)
                        append("\n有效期限：")
                        append(startDate)
                        append(" - ")
                        append(endDate)
                    }
                }

                append("\n\n耗时：$distime ms")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HHTipUtils.getInstance().dismissProgressDialog()
        mainHandler.removeCallbacksAndMessages(null)
        readCardManager.readCardStop()
    }
}